"""
文档处理工具模块
"""

from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.shared import qn
from langchain_core.tools import tool
import os

def modify_document_format(doc_path: str, style_format_mapping: dict, output_path: str = None):
    """
    遍历 Word 文档的段落，根据其样式应用指定的格式。

    Args:
        doc_path (str): 输入 Word 文档的路径。
        style_format_mapping (dict): 一个字典，键是样式名（如 '标题 1'），值是包含格式设置的字典。
                                    格式字典可以包含以下键：
                                    - 'font_name' (str): 字体名称 (如 '黑体')
                                    - 'font_size' (int): 字号 (单位：磅)
                                    - 'bold' (bool): 是否加粗
                                    - 'italic' (bool): 是否倾斜
                                    - 'underline' (bool): 是否下划线
                                    - 'alignment' (str): 对齐方式 ('left', 'center', 'right', 'justify')
                                    - 'space_before' (float): 段前间距 (单位：磅)
                                    - 'space_after' (float): 段后间距 (单位：磅)
                                    - 'line_spacing' (float): 行距 (倍数)
        output_path (str, optional): 输出文档的路径。如果为 None，则覆盖原文件。

    Returns:
        bool: 操作成功返回 True，否则返回 False。
    """
    try:
        # 加载文档
        doc = Document(doc_path)

        # 遍历文档中的所有段落
        for paragraph in doc.paragraphs:
            # 获取段落的样式
            paragraph_style = paragraph.style.name

            # 检查该样式是否在映射字典中
            if paragraph_style in style_format_mapping:
                format_settings = style_format_mapping[paragraph_style]
                run = paragraph.runs[0] if paragraph.runs else paragraph.add_run()

                # 设置字体
                if 'font_name' in format_settings:
                    # 设置西文字体
                    run.font.name = format_settings['font_name']
                    # 设置中文字体 (使用 XML 方法)
                    run._element.rPr.rFonts.set(qn('w:eastAsia'), format_settings['font_name'])

                # 设置字号
                if 'font_size' in format_settings:
                    run.font.size = Pt(format_settings['font_size'])

                # 设置加粗
                if 'bold' in format_settings:
                    run.bold = format_settings['bold']

                # 设置倾斜
                if 'italic' in format_settings:
                    run.italic = format_settings['italic']

                # 设置下划线
                if 'underline' in format_settings:
                    run.underline = format_settings['underline']

                # 设置段落格式
                paragraph_format = paragraph.paragraph_format

                # 设置段前间距
                if 'space_before' in format_settings:
                    paragraph_format.space_before = Pt(format_settings['space_before'])

                # 设置段后间距
                if 'space_after' in format_settings:
                    paragraph_format.space_after = Pt(format_settings['space_after'])

                # 设置对齐方式
                if 'alignment' in format_settings:
                    alignment_map = {
                        'left': WD_ALIGN_PARAGRAPH.LEFT,
                        'center': WD_ALIGN_PARAGRAPH.CENTER,
                        'right': WD_ALIGN_PARAGRAPH.RIGHT,
                        'justify': WD_ALIGN_PARAGRAPH.JUSTIFY
                    }
                    alignment = format_settings['alignment'].lower()
                    if alignment in alignment_map:
                        paragraph.alignment = alignment_map[alignment]

                # 设置行距
                if 'line_spacing' in format_settings:
                    paragraph_format.line_spacing = format_settings['line_spacing']

        # 确定输出路径
        save_path = output_path if output_path else doc_path

        # 保存文档
        doc.save(save_path)
        print(f"文档格式修改成功，已保存至: {save_path}")
        return True

    except Exception as e:
        print(f"修改文档格式时发生错误: {e}")
        return False